/**
 * 消息服务的模型
 * Created by jinlei on 14-10-10.
 */

var tv4 = require('tv4');

var iconsSchema = {
  type: "object",
  properties: {
    largeImageUrl: {
      type: 'string'
    },
    smallImageUrl: {
      type: 'string'
    }
  },
  required: ["largeImageUrl", "smallImageUrl"]
};

var interfaceSchema = {
  type: "object",
  properties: {
    name: {
      type: 'string'
    },
    title: {
      type: 'string'
    },
    description : {
      type: 'string'
    },
    url: {
      type: 'string'
    },
    actionType: {
      type: 'string'
    },
    schemaUrl: {
      type: 'string'
    }
  },
  required: ["name", "title", "url", 'actionType']
};

var interfacesSchema = {
  type:"array",
  items: {$ref: "#interface"}
}


module.exports = {

  types: {
    description: function (value) {
      return true;
    }
  },

  attributes: {
    name: {
      type: 'string',
      required: true,
      unique: true,
      description: '消息服务的名称, 必须唯一'
    },
    secret:{
      type:'string',
      description: '消息服务的授权码，用于在认证中取得token使用。'
    },
    redirectUri:{
      type:'string',
      description: '授权后重定向的回调链接地址'
    },
    title: {
      type: 'string',
      required: true,
      description: '消息服务的显示名称'
    },
    description: {
      type: 'string',
      required: true,
      description: '消息服务的文字描述'
    },
    icons: {
      type: 'json',
      required: true,
      description: '消息服务的图标URL路径配置'
    },
    interfaces: {
      type: 'json',
      required: true,
      description: '消息服务提供给手机客户端的接口地址'
    }
  },
  beforeCreate:function(values, next) {

  },

  beforeValidate:function(values, next) {


    async.series([

      //校验icons的格式
      function(cb) {

        var result = tv4.validateResult(values.icons, iconsSchema, {additionalProperties:true}, true);

        if (result.valid) {
          cb(null, true);
        } else {
          cb(result.error, false);
        }
      },

      //校验interfaces的格式
      function(cb) {
        tv4.addSchema("#interface", interfaceSchema);
        var result = tv4.validateResult(values.interfaces, interfacesSchema, {additionalProperties:true}, true);

        if (result.valid) {
          cb(null, true);
        } else {
          cb(result.error, false);
        }
      }

    ], function(errors, valids){

      if (errors) {
        return next(errors);
      } else {
        next();
      }

    });

  }
}